#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string>
#include<cstring>

#define PORT 6666

int main(int argc, char* argv[])
{
	//if(argc != 2)
	//{
	//	std::cout<<"参数不足!\n";
	//	return 1;
	//}
	int sock = socket(AF_INET,SOCK_DGRAM,0);
	std::cout<<"sock: "<<sock<<std::endl;
	
	struct sockaddr_in local;
	local.sin_family = AF_INET;
	local.sin_port = htons(PORT);
	local.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)
	{
		std::cerr<<"bind error!"<<std::endl;
		return 2;
	}
	char message[1024];
	while(1)
	{
		memset(message,'\0',sizeof(message));
		struct sockaddr_in other;
		socklen_t len = sizeof(other);
		ssize_t s = recvfrom(sock,message,sizeof(message)-1,0,(struct sockaddr*)&other,&len);
		if(s > 0)
		{
			FILE* in = popen(message,"r");
			if(in == nullptr)
				continue;
			std::string echo_message;
			char line[128];
			while(fgets(line,sizeof(line),in))
			{
				echo_message += line;
			}
			sendto(sock,echo_message.c_str(),echo_message.size(),0,(struct sockaddr*)&other,len);
			pclose(in);
		}
	}
	close(sock);
	return 0;
}

